package city.spring.service.impl;

import city.spring.domain.entity.UnitmeasurementEntity;
import city.spring.repository.UnitmeasurementRepository;
import city.spring.service.UnitmeasurementService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * Service：计量单位
 *
 * @author 谢金婷
 * @date 2020-05-06 09:29:54
 */
@CacheConfig(cacheNames = {UnitmeasurementServiceImpl.CACHE_NAME})
@Transactional(rollbackFor = Throwable.class)
@Service
public class UnitmeasurementServiceImpl extends ServiceImpl<UnitmeasurementRepository, UnitmeasurementEntity> implements UnitmeasurementService {

    private final UnitmeasurementRepository unitmeasurementRepository;

    public UnitmeasurementServiceImpl(UnitmeasurementRepository unitmeasurementRepository) {
        this.unitmeasurementRepository = unitmeasurementRepository;
    }

    @Override
    public void saveUnitmeasurement(UnitmeasurementEntity entity) {
        //如果转换关系为null，则设置为1
        if (entity.getRelationship() == null) {
            entity.setRelationship(new BigDecimal(1));
        }
        if (entity.getDeputyUnit() == null) {
            entity.setDeputyUnit(entity.getMeasurement());
        }
        if (!save(entity)) {
            throw new RuntimeException("保存信息失败");
        }
    }

    @Override
    public void updateUnitmeasurement(UnitmeasurementEntity entity) {
        // 使用 updateById(entity); 修改数据时，将会修改 entity 对象中所有非null数据，如果某个字段为null，将会忽略该字段的修改
        boolean update = updateById(entity);
        if (!update) {
            throw new RuntimeException("修改信息失败");
        }
    }

    @Override
    public void deleteUnitmeasurement(String primaryKey) {
        removeById(primaryKey);
    }

    @Override
    public void deleteUnitmeasurement(List<String> primaryKeys) {
        removeByIds(primaryKeys);
    }

    /**
     * 查询单位，按创建时间排序
     *
     * @return
     */
    @Override
    public List<UnitmeasurementEntity> getUnitmeasurementByOrder() {
        return unitmeasurementRepository.getUnitmeasurementByOrder();
    }

}